package cn.zwx.business.order.remote;

import cn.zwx.business.order.annotation.ZwxRemoteService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 *  自定义BeanPostProcessor实现类
 *  BeanPostProcessor接口的作用是：
 * 我们可以通过该接口中的方法在bean实例化、配置以及其他初始化方法前后添加一些我们自己的逻辑
 * @author zhangwenxue
 */
@Component
public class InitMediator implements BeanPostProcessor {

    private static final List<String> excludes = Arrays.asList("wait","toString","equals","hashCode","getClass","notifyAll","notify");
    /**
     * 这里去
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        if (aClass.isAnnotationPresent(ZwxRemoteService.class)){
            // 获取bean所有public修饰的方法 缓存进入Map
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if (excludes.contains(method.getName())){
                    continue;
                }
                // Object自带方法忽略掉 这里写死第一个 后面可以优化掉
                String key =  aClass.getInterfaces()[0].getName()+"."+ method.getName()+"."+ Arrays.toString(method.getParameterTypes());
                BeanMethod beanMethod = new BeanMethod();
                beanMethod.setBean(bean);
                beanMethod.setMethod(method);
                Mediator.mapCache.put(key,beanMethod);
            }
        }
        return bean;
    }
}
